package com.emo.cloudEdge.util;

import com.emo.cloudEdge.pojo.User;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * json工具
 */
@Component
public class Gson{
    @Autowired
    private ObjectMapper objectMapper;
    @Getter
    private String jsonStr;

    public Gson(){}
    public Gson(String jsonStr){
        this.jsonStr=jsonStr;
    }

    public void setJsonStr(String jsonStr) {
        this.jsonStr = jsonStr;
    }

    /**
     * 把对象转化为Json格式
     * @param data
     * @return
     */
    public String toJson(Object data){
        String res=null;
        try {
            res=objectMapper.writeValueAsString(data);
        }catch (Exception e){
            System.out.println("Gson toJson error .....");
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 解析json字符串
     * @param parameter
     * @return
     */
    public String getJson(String parameter){
        try{
            JsonNode jsonNode = objectMapper.readTree(jsonStr);
            return jsonNode.get(parameter).asText();
        }catch (Exception e){
            System.out.println("Gson getJson error .....");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取Json节点
     * @return
     */
    public JsonNode getJsonNode(){
        try {
            return objectMapper.readTree(jsonStr);
        }catch (Exception e){
            System.out.println("Gson getJsonNode error .....");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取json对象
     * @param objectClass
     * @return
     */
    public Object readValueObject(Class objectClass){
        try{
            return objectMapper.readValue(jsonStr, objectClass);
        }catch (Exception e){
            System.out.println("Gson readValueObject error .....");
            e.printStackTrace();
        }
       return null;
    }
}
